package com.xdhl.fu.member.consumer;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xdhl.fu.common.core.constant.event.MemberServiceEnvUpdateConstants;
import com.xdhl.fu.common.core.utils.StringUtils;
import com.xdhl.fu.member.domain.MemberBasic;
import com.xdhl.fu.member.service.IMemberBasicService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员服务环境事件消费者
 *
 * @author 朱力维
 * @time 2022/6/7 17:08
 */
@Component
public class MemberServiceEnvUpdateEventConsumer {

    private static final Logger log = LoggerFactory.getLogger(MemberServiceEnvUpdateEventConsumer.class);

    @Value("#{'${spring.application.name}'+'-'+'${spring.profiles.active}'}")
    private String consumerGroup;

    @Value("${fu.rocketmq.namesrv-addr}")
    private String namesrvAddr;

    private DefaultMQPushConsumer consumer;

    @Resource
    private IMemberBasicService memberBasicService;

    private Map<String, String> envMapping;

    public static final String PROD = "prod";

    @PostConstruct
    public void init() throws MQClientException {
        consumer = new DefaultMQPushConsumer(consumerGroup);
        consumer.setNamesrvAddr(namesrvAddr);

        //设置consumer所订阅的Topic和Tag，*代表全部的Tag
        consumer.subscribe(MemberServiceEnvUpdateConstants.TOPIC, "*");

        /**
         * CONSUME_FROM_LAST_OFFSET 默认策略，从该队列最尾开始消费，跳过历史消息
         * CONSUME_FROM_FIRST_OFFSET 从队列最开始开始消费，即历史消息（还储存在broker的）全部消费一遍
         */
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);

        consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> doing(list));
        consumer.start();

        envMapping = new HashMap<>();
        envMapping.put("prod", "A");
        envMapping.put("gray", "B");
        log.info("会员服务环境事件消费者启动成功。");
    }


    @PreDestroy
    public void destory() {
        consumer.shutdown();
        log.info("会员服务环境事件消费者已销毁。");
    }

    @Transactional
    public ConsumeConcurrentlyStatus doing(List<MessageExt> msgs) {
        ConsumeConcurrentlyStatus consumeConcurrentlyStatus;
        try {
            for (MessageExt msg : msgs) {
                JSONObject data = JSONObject.parseObject(new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET));
                String envCode = data.getString("envCode");
                String memberDataIds = data.getString("memberDataIds");
                String updateModel = data.getString("updateModel");

                // 全局更新前需要初始化所有用户的环境为正式环境，增量更新模式下不需要初始化其他用户
                if ("1".equals(updateModel)) {
                    MemberBasic update = new MemberBasic();
                    // 默认所有用户都是正式环境
                    update.setServiceEnv(envMapping.get(PROD));

                    LambdaQueryWrapper<MemberBasic> wrapper = new LambdaQueryWrapper<>();
                    wrapper.ne(MemberBasic::getServiceEnv, envMapping.get(PROD));
                    memberBasicService.update(update, wrapper);
                }

                if (StringUtils.isNotBlank(memberDataIds)) {
                    String[] dataIds = memberDataIds.split(",");

                    for (String dataId : dataIds) {
                        MemberBasic memberBasic = memberBasicService.getById(dataId);
                        if (null != memberBasic) {
                            // 设置为金丝雀环境
                            memberBasic.setServiceEnv(envMapping.get(envCode));
                            memberBasicService.updateById(memberBasic);
                        }
                    }
                }
            }
            consumeConcurrentlyStatus = ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        } catch (Exception e) {
            log.error(e.getMessage());
            consumeConcurrentlyStatus = ConsumeConcurrentlyStatus.RECONSUME_LATER;
            // nothing to do.
        }
        return consumeConcurrentlyStatus;
    }

}
